import json

from lxml import etree
import requests


headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cache-Control": "max-age=0",
    "Connection": "keep-alive",
    "Content-Type": "application/x-www-form-urlencoded",
    "Origin": "https://www.bjcourt.gov.cn",
    "Referer": "https://www.bjcourt.gov.cn/cpws/index.htm?st=1&q=&sxnflx=0&prompt=&dsrName=&ajmc=&ajlb=&jbfyId=5&zscq=&ay=&ah=&cwslbmc=&startCprq=2021-01-04&endCprq=2021-01-08&startFbrq=&endFbrq=&page=10",
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-User": "?1",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
    "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\""
}
cookies = {
    "thguid-r": "1776957059204378624",
    "__jsluid_s": "95d42844131b870d84c149d43eb2cc7d",
    "JSESSIONID": "node01nv9duupafaszy9dlmh0pywv463762300.node0",
    "vh2PJqrvyx": "MDAwM2IyYWYxZTQwMDAwMDAwMDQwXmAbOQYxNzUxOTE5MTE2",
    "6JDgKK8lEy": "MDAwM2IyYWYxZTQwMDAwMDAwMDMwRnMvDEExNzUxOTE5MTE2"
}
url = "https://www.bjcourt.gov.cn/cpws/index.htm"
data = {
    "ajlb": "0",
    "st": "1",
    "jbfyId": "1",
    "sxnflx": "0",
    "zscq": "",
    "cwslbmc": "",
    "prompt": "",
    "dsrName": "",
    "ajmc": "",
    "ay": "",
    "ah": "",
    "startCprq": "2021-01-04",
    "endCprq": "2021-01-08"
}
response = requests.post(url, headers=headers, cookies=cookies, data=data)

html_str = response.content.decode()
root = etree.HTML(html_str)
data_list = root.xpath("//div[@id='cpws-new-jbfy']/span[@class='fd-pl0' or 'no-span']")
result_list = []
for data in data_list:
    court = "".join(data.xpath("./@title"))
    court_name = "".join(data.xpath("./text()"))
    value_id = "".join(data.xpath("./input/@value"))
    result_list.append({"court": court, "court_name": court_name, "value_id": value_id})

with open('result.json', 'w', encoding='utf-8') as f:
    json.dump(result_list, f, ensure_ascii=False, indent=4)
